package com.apes.autoparts.parts.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.parts.model.AutoModel;
import com.apes.autoparts.parts.model.MainGroup;
import com.apes.autoparts.parts.model.SubGroup;
import com.apes.autoparts.parts.repository.AutoModelRepository;
import com.apes.autoparts.parts.repository.MainGroupRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("queryMainGroupService")
public class QueryMainGroupService extends DomainService {

    @Autowired
    private MainGroupRepository mainGroupRepository;

    @Autowired
    private AutoModelRepository autoModelRepository;

    @Autowired
    private ApiAutoParts91Service apiService;

    @Autowired
    private QuerySubGroupService querySubGroupService;

    @Autowired
    private SequenceService sequenceService;
    /***
     * 入口
     * @return
     */
    public JSONArray queryMainGroup(SimpleRequest request) {

        JSONObject param = request.getJO();

        List<AutoModel> autoModels = autoModelRepository.findAll(JpaDsl.toCriteriaByEq(
                "selectorId", param.getString("selectorId")
        ));
        JSONArray response = apiService.queryMainGroup(param);
        if (response == null)
            response = new JSONArray();

        return response;
    }

    public List<MainGroup> queryMainGroupAll(JSONObject param) {

        List<AutoModel> autoModels = autoModelRepository.findAll(JpaDsl.toCriteriaByEq(
                "selectorId", param.getString("id")
        ));
        JSONArray response = apiService.queryMainGroup(param);
        List<MainGroup> mainGroups = handleResponse(response, autoModels.get(0));
        mainGroups.forEach(mainGroup -> {
            mainGroupRepository.saveAndFlush(mainGroup);
        });
        return mainGroups;
    }


    /***
     * 处理返回值
     */

    private List<MainGroup> handleResponse(JSONArray param, AutoModel autoModel) {
        //将第三方数据转化成主组
        JSONArray mainGroupArray = param;
        List<MainGroup> mainGroupList = new ArrayList();
        for (int i = 0; i < mainGroupArray.size(); i++) {
            MainGroup mainGroup = new MainGroup();
            mainGroup.setId(sequenceService.getId(MainGroup.CONST_TABLE_NAME));
            mainGroup.setBelongTo(mainGroupArray.getJSONObject(i).getBoolean("isBelongTo"));
            String orgImageUrl = mainGroupArray.getJSONObject(i).getString("imageUrl");

            // 保存图片
            String imgUrl;
            try {
                imgUrl = apiService.saveImgToFtp(orgImageUrl);
                mainGroup.setImageUrl(imgUrl);
            } catch (Exception e) {
                mainGroup.setValid(false);
                mainGroup.setNote("图片保存失败");
            }

            mainGroup.setOrgImageUrl(orgImageUrl);

            mainGroup.setCode(mainGroupArray.getJSONObject(i).getString("code"));
            mainGroup.setName(mainGroupArray.getJSONObject(i).getString("name"));
            mainGroupList.add(mainGroup);
            mainGroup.setSelectorId(mainGroupArray.getJSONObject(i).getString("selectorId"));
            mainGroup.setMainGroupId(mainGroupArray.getJSONObject(i).getString("id"));
            mainGroup.setOrgSelectorId(autoModel);
            mainGroup.setTimestamp(new Date());
        }
        return mainGroupList;
    }

    public List<MainGroup> queryMainGroupAll(SimpleRequest request){
        JSONObject param = request.getJO();

        // 查看之前是否有处理过的单据
        List<MainGroup> mainGroups = mainGroupRepository.findAll(
                JpaDsl.toCriteriaByEq(
                        "orgSelectorId.id", param.getString("selectorId")
                )
        );
        // 获取第三方数据
        AutoModel autoModel = autoModelRepository.findOne(param.getString("selectorId"));

        // 查询所有主组里没有子组的信息
        if(mainGroups.size() != 0) {
            mainGroups.forEach(mainGroup -> {
                mainGroupRepository.saveAndFlush(mainGroup);
            });

            for (MainGroup mainGroup : mainGroups) {

                //查子组数据
                JSONObject jo = request.getJO();
                jo.put("id", mainGroup.getId());
                request.setData(jo);
                List<SubGroup> subGroupList = querySubGroupService.querySubGroupAll(request);

            }
            // 查询所有主组里子组的信息
        } else {

            param.put("selectorId", autoModel.getSelectorId());
            JSONArray response = apiService.queryMainGroup(param);
            // 处理返回值并保存
            mainGroups = handleResponse(response, autoModel);

            mainGroups.forEach(mainGroup -> {
                mainGroupRepository.saveAndFlush(mainGroup);
            });

            for (MainGroup mainGroup : mainGroups) {

                //子组数据
                JSONObject jo = request.getJO();
                jo.put("id", mainGroup.getId());
                jo.put("selectorId", autoModel.getId());
                request.setData(jo);
                List<SubGroup> subGroupList = querySubGroupService.querySubGroupAll(request);

            }
        }
        return mainGroups;
    }


    // 检验主组数据
    public boolean checkMainGroupData(JSONObject request) {
        // 有数据返回true，没数据返回false
        boolean check = true;
        JSONObject mainGroupApi = new JSONObject();
        mainGroupApi.put("vin", request.getString("vin"));
        mainGroupApi.put("id", request.getString("selectorId"));
        mainGroupApi.put("brandCode", request.getString("brandCode"));
        try {
            JSONArray mainGroup = apiService.queryMainGroup(mainGroupApi);
            if (mainGroup == null && mainGroup.size() == 0)
                check = false;
        } catch (Exception e) {
            check = false;
        }
        return check;
    }
}
